import React,{useState, useEffect,} from 'react';
import marked from 'marked';
import '../static/css/AddArticle.css';
import { Row, Col ,Input, Select ,Button ,DatePicker, message } from 'antd';
import axios from 'axios';
import servicePath from '../config/api';

const { Option } = Select;
const { TextArea } = Input;

function AddArticle(props) {

  
   const [articleId, setArticleId] =useState(0)  //文章的 ID ，如果是0则说明是新增的 如果不是0则是修改  
   const [articleTitle, setArticleIitle] =useState('')  //文章标题
   const [articleContent, setArticleContent] =useState('')  //makeddown 编辑内容
   const [markdownContent, setMarkDownContent] =useState('预览内容')  //编辑后的预览内容  
   const [introducemd,setIntroducemd] = useState()            //简介的markdown内容
   const [introducehtml,setIntroducehtml] = useState('') //简介的html内容
   const [showDate,setShowDate] = useState()   //发布日期
//    const [updateDate,setUpdateDate] = useState() //修改日志的日期
   const [typeInfo ,setTypeInfo] = useState([]) // 文章类别信息
   const [selectedType,setSelectType] = useState('请选择类别') //选择的文章类别   
 


  useEffect(()=>{
    getTypeInfo()
    // 获取文章 ID
    let tmpId = props.match.params.id
    console.log(tmpId)
     if(tmpId){
        setArticleId(tmpId)
        getArticleById(tmpId)
     }
  },[])   // 空数组表示只执行一次


   marked.setOptions({
    renderer: new  marked.Renderer(),  //renderer: 这个是必须填写的，你可以通过自定义的Renderer渲染出自定义的格式
    gfm: true,
    pedantic: false,
    sanitize: false,
    tables: true,
    breaks: false,
    smartLists: true,
    smartypants: false
  }); 

  //选择类别后的便哈
  const selectTypeHandler =(value)=>{
    setSelectType(value)
}

  const  changeContent = (e)=>{
    setArticleContent(e.target.value)
    let html = marked(e.target.value)
    setMarkDownContent(html)
  }

  const changeIntroduce =(e)=>{
    setIntroducemd(e.target.value)
    let html = marked(e.target.value)
    setIntroducehtml(html)
  }
  
  const  getTypeInfo = ()=>{
      axios ({
          method: 'get',
          url : servicePath.getTypeInfo,
          header : {'Acces-Control-Allow-Origin' : '*'},
          withCredentials : true
      }).then(
          res=>{
              if(res.data.data==='没有登录'){
                  localStorage.removeItem('openId')
                  props.history.push('/')
              }else{                          //登录成功
                  setTypeInfo(res.data.data)
              }
          }
      )
  }

  const  saveArticle = ()=>{
   
      if(!selectedType){
          message.error('必须选择文章类型')
          return  false
      }else if(!articleTitle){
          message.error('文章标题不为空')
          return  false
      }else if(!articleContent){
        message.error('文章内容不为空')
        return  false
    }else if(!introducemd){
        message.error('文章简介不为空')
        return  false
    }else if(!showDate){
        message.error('发布日期不为空')
        return  false
    }
      let dataProps = {}  //传递到接口的参数
      dataProps.type_id = selectedType
      dataProps.title = articleTitle
      dataProps.article_content = articleContent
      dataProps.introduce = introducemd
      let dateText = showDate.replace('-','/')
      dataProps.addTime = (new Date(dateText).getTime())/ 1000

    if(articleId===0){
        dataProps.view_count = 0;
        axios ({
            method: 'post',
            url : servicePath.addArticle,
            data: dataProps,
            header:{ 'Access-Control-Allow-Origin':'*' },
            withCredentials : true
        }).then(
            res=>{
                setArticleId(res.data.insertId) 
                if(res.data.isSuccess){
                    message.success('文章添加成功 ')
                }else{
                    message.error('文章添加失败 ')
                }

                
            }
        )
    }else{
        
        dataProps.id = articleId
        axios ({
            method: 'post',
            url : servicePath.updateArticle,
            data: dataProps,
            withCredentials : true
        }).then(
            res=>{
               
                if(res.data.isSuccess){
                    message.success('文章保存成功 ')
                }else{
                    message.error('文章保存失败 ')
                }
            }
        )
    }

  }

  const getArticleById=(id)=>{
      console.log('===========',id)
      axios(servicePath.getArticleById+id,{
          withCredentials: true,
          header : {'Access-Control-Allow-Origin':'*' }
      }).then(
          res=>{
           let articleInfo = res.data.data[0]
           console.log(articleInfo)
           setArticleIitle(articleInfo.title)
           setArticleContent(articleInfo.article_content)
           let html = marked(articleInfo.article_content)
           setMarkDownContent(html)
           setIntroducemd(articleInfo.introduce)
           let tmpInt = marked(articleInfo.introduce)
           setIntroducemd(tmpInt)
           setShowDate(articleInfo.addTime)
           setSelectType(articleInfo.typeId)



          }
      )
  }
    return (
        <div>
            <Row gutter={5}>
                <Col span={18}>
                    <Row gutter={10}>
                        <Col span={20} >
                            <Input
                                value={articleTitle}
                                onChange={e=>{setArticleIitle(e.target.value)}}
                                placeholder="博客标题"
                                size="large"
                            />
                        </Col>
                        <Col span={4}>
                            &nbsp;
                      <Select defaultValue={selectedType} size="large" onChange={selectTypeHandler}>
                                {
                                    typeInfo.map((item, index) => {
                                    return <Option key={index} value={item.id}>{item.typeName}</Option>
                                    })
                                }
                        </Select>
                        </Col>
                    </Row>
                    <br />
                    <Row gutter={10}>
                        <Col span={12}>
                            <TextArea
                                value={articleContent}
                                onChange={changeContent}
                                onPressEnter={changeContent}
                                className="markdown-content"
                                rows={25}
                                placeholder="文章内容"
                            />
                        </Col>
                        <Col span={12}>
                            <div 
                               className="show-html"
                               dangerouslySetInnerHTML={{__html:markdownContent}}
                            >
                            </div>
                        </Col>
                    </Row>
                </Col>
                <Col span={6}>
                    <Row>
                        <Col span={24}>
                            <Button size='large'>暂存文章</Button>&nbsp;
                            <Button type="primary" size="large" onClick={saveArticle} >发布文章</Button>
                            <br />
                        </Col>
                        <Col span={24}>
                            <br />
                            <TextArea
                                value ={introducemd}
                                onChange={changeIntroduce}
                                onPressEnter={changeIntroduce}
                                rows={8}
                                placeholder="文章简介"
                               
                             />
                            <br /><br />
                            <div 
                                 className="introduce-html"
                                 dangerouslySetInnerHTML={{__html:"简介预览:"+introducemd}}
                                 >
                            </div>
                        </Col>
                        <Col span={12}>   
                            <div className="date-select">
                                <DatePicker
                                    onChange= {(date,dateString)=>{
                                        setShowDate(dateString)
                                    }}
                                    placeholder="发布日期"
                                    size="large">
                                </DatePicker>
                            </div>
                        </Col>
                        
                    </Row>
                </Col>
            </Row>
        </div>
    )
}
export default AddArticle;